//
//  AddLukyMoneyShowView.m
//  meiyinxiang
//
//  Created by apple on 2017/11/6.
//  Copyright © 2017年 hbjApple. All rights reserved.
//
#define kRequestTime 2.0f
#define kDelay 1.0f
#import "AddLukyMoneyShowView.h"
#import "LuckyMoneyViewController.h"
#import "MYXForgotPasswordViewController.h"
#import "LuckyMoneyVocherController.h"
#import "MYXRechargeViewController.h"

#import "MYXMemberMdel.h"
#import "MYXPayPasswordViewController.h"
#import "CYPasswordView.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "AppDelegate.h"
#import <POP.h>
#import "VocherViewModel.h"

#import "VocherHelper.h"
@interface AddLukyMoneyShowView ()
{
    VocherViewModel *vocherViewModel;
}
@property (nonatomic, strong) CYPasswordView *passwordView;
@property (weak, nonatomic) IBOutlet UIView *backGroundView;
@property (weak, nonatomic) IBOutlet UIImageView *xiangImageView;
@property (weak, nonatomic) IBOutlet UIImageView *hongbaoImageView;
@property (weak, nonatomic) IBOutlet UITextField *moneyTextfiel;
@property (weak, nonatomic) IBOutlet UITextField *moneyCountTextfield;
//红包券

@property (weak, nonatomic) IBOutlet UIButton *vocherBtn;
- (IBAction)voucherBtn:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *cashMoneyBtn;
//塞钱进红包
- (IBAction)cashMoneyBtn:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *realMoneyLabel;


@end

@implementation AddLukyMoneyShowView
static BOOL flag = NO;
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
+ (AddLukyMoneyShowView *)loadNibWithLukyMoneyShowView{
    UINib *nib = [UINib nibWithNibName:@"AddLukyMoneyShowView" bundle:[NSBundle mainBundle]];
    return [[nib instantiateWithOwner:nil options:nil] lastObject];
}
- (void)awakeFromNib{
    [super awakeFromNib];
    [self addTextfildNoticeKVO];
}
#pragma mark - PrivateMethod
- (void)addTextfildNoticeKVO{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moneyTextChange) name:UITextFieldTextDidChangeNotification object:self.moneyTextfiel];
}
- (void)moneyTextChange{
   // self.moneyTextfiel.text = [NSString stringWithFormat:@"%.1f",self.moneyTextfiel.text.floatValue];
    if (vocherViewModel == nil) {
         self.realMoneyLabel.text = [NSString stringWithFormat:@"¥%.1f",self.moneyTextfiel.text.floatValue];
    }else{
        if (self.moneyTextfiel.text.floatValue < vocherViewModel.condition.floatValue) {
            self.moneyTextfiel.text = vocherViewModel.condition;
            
        }
//        if (![vocherViewModel.condition2 isEqualToString:@"0"] && vocherViewModel.condition2) {//判断是否为限定红包个数
//            self.moneyCountTextfield.text = vocherViewModel.condition2;
//           // self.moneyCountTextfield.enabled = NO;
//        }else{
//            //self.moneyCountTextfield.enabled = YES;
//
//        }
        if ([vocherViewModel.is_add isEqualToString:@"0"]) {//判断是否为可改变金额条件
            self.moneyTextfiel.text = vocherViewModel.num;
            self.moneyTextfiel.enabled = NO;
        }else{
            self.moneyTextfiel.enabled = YES;

        }
        self.realMoneyLabel.text = [[VocherHelper shared] figureOutWithAllMoney:self.moneyTextfiel.text withVocher:vocherViewModel];
    }
   
}
- (void)addTapGes{
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMiss)];
    self.backGroundView.userInteractionEnabled = YES;
    [self.backGroundView addGestureRecognizer:tapGes];
    self.hongbaoImageView.userInteractionEnabled = YES;
    self.xiangImageView.userInteractionEnabled = YES;
    
}
- (void)tapMiss{

    //缩放动画
    POPBasicAnimation *scaleAnim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewScaleXY];
    scaleAnim.fromValue = [NSValue valueWithCGPoint:CGPointMake(1, 1)];
    scaleAnim.toValue = [NSValue valueWithCGPoint:CGPointMake(0.1, 0.1)];
    scaleAnim.duration = 0.5;
    [self pop_addAnimation:scaleAnim forKey:nil];
    scaleAnim.completionBlock = ^(POPAnimation *anim, BOOL finished) {
        
        self.hidden = YES;
    };
}
//添加红包动画
- (void)addLuckyMoneyAnnamation{


    self.hidden = NO;
    self.center = self.mSuperViewController.view.center;
    self.bounds = self.mSuperViewController.view.bounds;
    //缩放动画
    POPBasicAnimation *scaleAnim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewScaleXY];
    scaleAnim.fromValue = [NSValue valueWithCGPoint:CGPointMake(0.1, 0.1)];
    scaleAnim.toValue = [NSValue valueWithCGPoint:CGPointMake(1, 1)];
    scaleAnim.duration = 0.5;
    [self pop_addAnimation:scaleAnim forKey:nil];
    [self addTapGes];
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.moneyTextfiel resignFirstResponder];
    [self.moneyCountTextfield resignFirstResponder];
}
//代金券
- (IBAction)voucherBtn:(id)sender {
        __weak LuckyMoneyViewController *weakVC = (LuckyMoneyViewController *)_mSuperViewController;
    
    LuckyMoneyVocherController *vocherVC = [[LuckyMoneyVocherController alloc] init];
    WS(weakself);
    vocherVC.selectBlock = ^(VocherViewModel  *viewModel) {
        vocherViewModel = viewModel;
        if (weakself.moneyTextfiel.text.floatValue < viewModel.condition.floatValue) {
            weakself.moneyTextfiel.text = viewModel.condition;
        }
        [weakself.vocherBtn setTitle:[NSString stringWithFormat:@"满%@减%@红包券",vocherViewModel.condition,vocherViewModel.num] forState:UIControlStateNormal];
        [weakself moneyTextChange];
    };
    [self.mSuperViewController.navigationController pushViewController:vocherVC animated:YES];
}
//塞钱进红包
- (IBAction)cashMoneyBtn:(id)sender {
    if (![[VocherHelper shared] figureOutMoney:self.moneyTextfiel.text moneyCount:self.moneyCountTextfield.text]) {//判定红包个数和金额条件
        return;
    }
    
    
    
    if ( [MYXMemberMdel sharedInstance].userinfo.paypassword.length == 0){
        //设置密码
        [self gotosettingpassword];
        return;
    }
    //支付密码
    [self payPassword];

    
}

- (void)gotosettingpassword{
    MYXForgotPasswordViewController *PasswordViewControl = [[MYXForgotPasswordViewController alloc] init];
    PasswordViewControl.selectBlock=^(NSString *payPassword){
        
        [MYXMemberMdel sharedInstance].userinfo.paypassword =payPassword;
        [[MYXMemberMdel sharedInstance] save];
    };
    PasswordViewControl.navigationItem.title =@"设置支付密码";
    PasswordViewControl.type=2;
    [self.mSuperViewController.navigationController pushViewController:PasswordViewControl animated:YES];
}
- (void)payPassword{
    /** 注册取消按钮点击的通知 */
    [CYNotificationCenter addObserver:self selector:@selector(cancel) name:CYPasswordViewCancleButtonClickNotification object:nil];
    [CYNotificationCenter addObserver:self selector:@selector(forgetPWD) name:CYPasswordViewForgetPWDButtonClickNotification object:nil];
    __weak typeof(self) weakself  = self;
    self.passwordView = [[CYPasswordView alloc] init];
    self.passwordView.title = @"输入交易密码";
    self.passwordView.loadingText = @"提交中...";
    [self.passwordView showInView:self];
    __weak LuckyMoneyViewController *weakVC = (LuckyMoneyViewController *)_mSuperViewController;
    self.passwordView.finish = ^(NSString *password) {
        [weakself.passwordView hideKeyboard];
        [weakself.passwordView startLoading];
        CYLog(@"cy ========= 发送网络请求  pwd=%@", password);
        NSString *lat = weakVC.rangeModel.lati;
        NSString *lon = weakVC.rangeModel.lon;
        NSString *title = @"1";
        NSString *content = weakVC.textCell.growTextView.text;
        //FIXME:添加图片url
        NSString *imgUlr = @"";
        for (NSInteger i = 0; i < weakVC.textCell.uploadImgArray.count; i++) {
            NSString *subImgstr = weakVC.textCell.uploadImgArray[i];
            if (i == 0) {
                imgUlr = [NSString stringWithFormat:@"%@",subImgstr];
            }else{
                imgUlr = [NSString stringWithFormat:@"%@,%@",imgUlr,subImgstr];
            }
        }
        NSString *file = imgUlr;
        ComposeMoneyModel *model = weakVC.compViewModel.modelArray[0];
        NSString *is_normal = [model.sectionCateTitle isEqualToString:@
                               "普通红包"] ? @"1" : @"0";
        ComposeMoneyModel * sexModel = weakVC.compViewModel.modelArray[1];
        NSString *sex = @"0";

        if ([sexModel.sectionCateTitle isEqualToString:@"全部"]) {
            sex = @"0";
        }else if ([sexModel.sectionCateTitle isEqualToString:@"仅限男生"]){
            sex = @"1";
        }else if ([sexModel.sectionCateTitle isEqualToString:@"仅限女生"]){
            sex = @"2";
        }
        NSString *rcount = [NSString stringWithFormat:@"%ld",weakself.moneyCountTextfield.text.integerValue];
        NSString *money = [NSString stringWithFormat:@"%f",weakself.moneyTextfiel.text.floatValue];
        
        NSString *radius = [NSString stringWithFormat:@"%ld",weakVC.rangeModel.locationRangeRadius/1000];
        NSString *ticketId = @"";
        if (vocherViewModel != nil) {
            ticketId = vocherViewModel.vocherid;
        }
        NSLog(@"%@,%@,%@，%@，%@，%@,%@,%@,%@，%@,%@,%@",lat,lon,title,content,file,is_normal,sex,rcount,money,radius,password,ticketId);
        [[MYXHttpManager shared] postLuckyMoneyWithlatitude:lat
                                                  longitude:lon
                                                      title:title
                                                    content:content
                                                       file:file
                                                  is_normal:is_normal
                                                        sex:sex rcount:rcount
                                                      money:money radius:radius paypassword:password ticket_id:ticketId  withResult:^(BOOL sucess, NSString *msg) {
            if (sucess) {
                [weakself.passwordView requestComplete:YES message:@"支付成功"];
                [weakself.passwordView stopLoading];
                [weakself.passwordView hide];
                [weakself tapMiss];
                [SVProgressHUD showSuccessWithStatus:@"发送红包成功"];
                [weakVC dismissViewControllerAnimated:YES completion:nil];

               
            }else{
                [weakself.passwordView requestComplete:NO message:msg];
                [weakself.passwordView stopLoading];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kRequestTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself.passwordView hide];
                    MYXRechargeViewController *MYXRechargeVC =[[MYXRechargeViewController alloc]init];
                    MYXRechargeVC.navigationItem.title = @"充值";
                    if ([msg hasPrefix:@"余额不足"]) {
                [weakself.mSuperViewController.navigationController pushViewController:MYXRechargeVC animated:YES];
                    }
                });
              
            }
        } errorResult:^(NSError *enginerError) {
            ShowSVProgressErrorMessage(@"网络出错！！");

           // [SVProgressHUD showErrorWithStatus:@"网络出错！！"];
           //  [weakVC dismissViewControllerAnimated:YES completion:nil];
        }];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kRequestTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            flag = !flag;
//            if (flag) {
//                CYLog(@"申购成功，跳转到成功页");
//                [weakself.passwordView requestComplete:YES message:@"申购成功，做一些处理"];
//                [weakself.passwordView stopLoading];
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [weakself.passwordView hide];
//                });
//            } else {
//                CYLog(@"申购失败，跳转到失败页");
//            }
//
//        });
    };
}
- (void)forgetPWD {
    CYLog(@"忘记密码");
}
- (void)cancel {
    CYLog(@"关闭密码框");
}
@end
